package com.pceggs.workwall;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.StatusUtil;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.cause.ResumeFailedCause;
import com.liulishuo.okdownload.core.listener.DownloadListener1;
import com.liulishuo.okdownload.core.listener.assist.Listener1Assist;
import com.pceggs.workwall.util.PceggsWallUtils;
import com.pceggs.workwall.util.SystemUtil;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 积分墙列表页
 * webView加载的url，建议由贵公司，后台直接拼接好，app直接打开即可,参数的具体含义看文档
 * 样式如下
 * webView.loadUrl("http://apptest.pceggs.com/Pages/IntegralWall/IW_Awall_adList.aspx?userid=" + userid + "&deviceid=" + imei + "&ptype=2&pid="+pid+"&keycode=" + keycode + "&newversion=1")
 * app端与H5交互的方法，直接拷入即可
 * <p>
 * 必须开启相应的权限，读写文件，读写设备，否则无法正常下载
 *
 * @author Administrator
 * @date 2018/6/12 15:03
 */
public class AdListActivity extends Activity {

    private static final int REQUEST_CODE = 0;//请求码
    //配置需要动态申请的权限
    private static final String[] permissions = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.INTERNET};//Manifest.permission.REQUEST_INSTALL_PACKAGES   Manifest.permission.CAMERA
    private android.app.AlertDialog mPermissionDialog;
    private String downUrlLocal = "";
    private String packagenameLocal = "";
    private WebView webView;
    private TextView tv_start_download;
    private List<String> mPermissionList = new ArrayList<>();
    private TextView tv_title;
    private RelativeLayout rl_back;
    private String pid;
    private String key;
    private String userId;

    private long timeout = 5000;
    private Timer timer;
    private String loadUrl;
    private int progress;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (null != timer) {
                        timer.cancel();
                        if (null != timer) {
                            timer.purge();
                        }

                        timer = null;
                    }
                    if (null != webView && !TextUtils.isEmpty(loadUrl)) {
                        webView.loadUrl(loadUrl);
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private String deviceId;
    private boolean isNoFirst = false;
    private String xwdeviceid;

    public static void launch(Activity activity, String pid, String key, String userId, String deviceId, String xwdeviceid) {
        Intent intent = new Intent(activity, AdListActivity.class);
        intent.putExtra("pid", pid);
        intent.putExtra("key", key);
        intent.putExtra("userId", userId);
        intent.putExtra("deviceId", deviceId);
        intent.putExtra("xwdeviceid", xwdeviceid);
        activity.startActivity(intent);
    }

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_ad_list_pceggs);

        webView = findViewById(R.id.webview);
        tv_start_download = findViewById(R.id.tv_start_download);
        tv_title = findViewById(R.id.tv_title);
        rl_back = findViewById(R.id.rl_back_pceggs);

        //获取传递过来的信息
        getBundleData();

        if (TextUtils.isEmpty(pid) || TextUtils.isEmpty(key) || TextUtils.isEmpty(userId)) {
            Log.d("pceggs_init", "请初始化pid以及appkey,userid");
        } else {
            Log.d("pceggs_init", "初始化成功,pid:" + pid + " appkey:" + key + " userId:" + userId);
        }

        //set webView
        initWebView();

        //返回键 git
        initToolbar();

        //Android6.0需要动态获取权限
        initPermission();

        //下载按钮触发事件
        tv_start_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //异常判断
                if (TextUtils.isEmpty(downUrlLocal)) {
                    Toast.makeText(AdListActivity.this, "下载连接异常", Toast.LENGTH_SHORT).show();
                    return;
                }

                //存在立即打开
                final boolean isInstalled = SystemUtil.isAppInstalled(AdListActivity.this, packagenameLocal);
                if (isInstalled) {
                    doStartApplicationWithPackageName(packagenameLocal);
                    return;
                }

                //执行下载
                int last = downUrlLocal.lastIndexOf("/") + 1;
                String apkName = downUrlLocal.substring(last);
                if (!apkName.contains(".apk")) {
                    if (apkName.length() > 10) {
                        apkName = apkName.substring(apkName.length() - 10);
                    }
                    apkName += ".apk";
                }
                String downloadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "pceggswall";// + File.separator + apkName;
                downLoadApp(apkName, downloadPath, downUrlLocal, tv_start_download);

                if (null != webView) {
                    //下载通知后台，js交互
                    webView.post(new Runnable() {
                        @Override
                        public void run() {
                            if (null != webView) {
                                webView.loadUrl("javascript:startDownApp()");
                            }
                        }
                    });
                }
            }
        });

        timer = new Timer();

        TimerTask tt = new TimerTask() {
            @Override
            public void run() {

                if (progress < 100) {
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                }
            }
        };

        if (null != timer) {
            timer.schedule(tt, timeout, timeout);
        }
    }

    private void getBundleData() {
        pid = getIntent().getStringExtra("pid");
        key = getIntent().getStringExtra("key");
        userId = getIntent().getStringExtra("userId");
        deviceId = getIntent().getStringExtra("deviceId");
        xwdeviceid = getIntent().getStringExtra("xwdeviceid");
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {

        if (null != webView) {

            //声明WebSettings子类
            WebSettings webSettings = webView.getSettings();

            //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
            webSettings.setJavaScriptEnabled(true);

            //设置自适应屏幕，两者合用
            webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
            webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

            //其他细节操作
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
            webSettings.setAllowFileAccess(true); //设置可以访问文件
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
            webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
            webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

            webSettings.setDomStorageEnabled(true);  // 开启 DOM storage 功能
            webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
            String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
            webSettings.setAppCachePath(appCachePath);
            webSettings.setAllowFileAccess(true);    // 可以读取文件缓存
            webSettings.setAppCacheEnabled(true);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }

            webView.addJavascriptInterface(AdListActivity.this, "android");
        }
    }

    protected void initToolbar() {

        rl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (null != webView && webView.canGoBack()) {
                    webView.goBack();
                } else {
                    if (webView != null) {
                        webView.stopLoading();
                        webView.clearHistory();
                        webView.clearCache(true);
                        webView.destroy();
                        webView = null;
                    }
                    if (null != timer) {
                        timer.cancel();
                        if (null != timer) {
                            timer.purge();
                        }
                        timer = null;
                    }
                    finish();
                }
            }
        });
    }

    /**
     * 权限判断和申请
     */
    private void initPermission() {
        mPermissionList.clear();//清空已经允许的没有通过的权限
        //逐个判断是否还有未通过的权限
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) !=
                    PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);//添加还未授予的权限到mPermissionList中
            }
        }
        //申请权限
        if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
            ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE);
        } else {
            //权限已经都通过了，可以将程序继续打开了
            //imei = SystemUtil.getDeviceId(this);
            openUrl();
        }
    }

    /**
     * 打开app
     *
     * @param packagename
     */
    private void doStartApplicationWithPackageName(String packagename) {
        try {
            Intent intent = getPackageManager().getLaunchIntentForPackage(packagename);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(AdListActivity.this, "没有安装", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 下载逻辑
     *
     * @param apkName
     * @param path
     * @param url
     * @param tv
     */
    public void downLoadApp(final String apkName, final String path, final String url, final TextView tv) {
        boolean completed = StatusUtil.isCompleted(url, path, apkName);

        if (completed) {
            install(AdListActivity.this, new File(path + File.separator + apkName), PceggsWallUtils.authoritiesLoc);
            return;
        }

        DownloadTask task = new DownloadTask.Builder(url, new File(path))
                .setFilename(apkName)
                // the minimal interval millisecond for callback progress
                .setMinIntervalMillisCallbackProcess(100)
                // do re-download even if the task has already been completed in the past.
                .setPassIfAlreadyCompleted(false)
                .setAutoCallbackToUIThread(true)
                .setConnectionCount(1)
                .build();

        task.enqueue(new DownloadListener1() {
            @Override
            public void taskStart(@NonNull DownloadTask task, @NonNull Listener1Assist.Listener1Model model) {

            }

            @Override
            public void retry(@NonNull DownloadTask task, @NonNull ResumeFailedCause cause) {

            }

            @Override
            public void connected(@NonNull DownloadTask task, int blockCount, long currentOffset, long totalLength) {

            }

            @Override
            public void progress(@NonNull DownloadTask task, long currentOffset, long totalLength) {

                if (totalLength == -1 || totalLength == 0) {
                    tv.setText("正在下载");
                } else {
                    int progress = (int) ((Long.valueOf(currentOffset) * 100) / Long.valueOf(totalLength));
                    tv.setText("正在下载" + "(" + progress + "%)");
                }

                tv.setEnabled(false);
            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull Listener1Assist.Listener1Model model) {
                Log.i("down:", "taskEnd...");
                try {
                    //installAPK(new File(path), apkName, PceggsWallUtils.authoritiesLoc);
                    install(AdListActivity.this, new File(path + File.separator + apkName), PceggsWallUtils.authoritiesLoc);
                } catch (Exception e) {

                }
                tv.setEnabled(true);
            }
        });

        /*BaseDownloadTask baseDownloadTask = FileDownloader.getImpl().create(url)
                .setPath(path)
                .setCallbackProgressTimes(100)
                .setMinIntervalUpdateSpeed(100)
                .setListener(new FileDownloadSampleListener() {

                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.pending(task, soFarBytes, totalBytes);
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.progress(task, soFarBytes, totalBytes);

                        if (totalBytes == -1) {
                            tv.setText("正在下载");
                        } else {
                            int progress = (int) ((Long.valueOf(soFarBytes) * 100) / Long.valueOf(totalBytes));
                            tv.setText("正在下载" + "(" + progress + "%)");
                        }

                        tv.setEnabled(false);
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        super.completed(task);
                        tv.setText("立即试玩");
                        try {
                            //installAPK(new File(path), apkName, PceggsWallUtils.authoritiesLoc);
                            install(AdListActivity.this, new File(path), PceggsWallUtils.authoritiesLoc);
                        } catch (Exception e) {

                        }
                        tv.setEnabled(true);
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.paused(task, soFarBytes, totalBytes);
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        super.error(task, e);
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        super.warn(task);
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        super.connected(task, etag, isContinue, soFarBytes, totalBytes);
                    }
                });

        baseDownloadTask.start();*/
    }

    private void openUrl() {

        if (null != webView) {
            webView.setWebChromeClient(new MyWebChromeClient());
            webView.setWebViewClient(new MyWebViewClient());

            String pidstr = pid;
            String appkey = key;
            String userid = userId;
            String ptype = "2";

            //pid+deviceid+ptype+userid+appkey
            String keycode = pidstr + deviceId + ptype + userid + appkey;
            keycode = string2MD5(keycode).toLowerCase();

            //loadUrl = "http://apptest.pceggs.com/Pages/IntegralWall/IW_Awall_adList.aspx?userid=" + userid + "&deviceid=" + deviceId + "&ptype=" + ptype + "&pid=" + pidstr + "&keycode=" + keycode + "&xwdeviceid=" + xwdeviceid;
            loadUrl = "https://sdkapi.xiangwanyx.com/Pages/IntegralWall/IW_Awall_adList.aspx?userid=" + userid + "&deviceid=" + deviceId + "&ptype=" + ptype + "&pid=" + pidstr + "&keycode=" + keycode + "&xwdeviceid=" + xwdeviceid;
            //https://sdkapi.xiangwanyx.com/

            //加载链接
            webView.loadUrl(loadUrl);
            Log.i("url:", loadUrl);
        }
    }

    /**
     * md5加密
     *
     * @param string
     * @return
     */
    public String string2MD5(String string) {

        if (TextUtils.isEmpty(string)) {
            return "";
        }

        MessageDigest md5 = null;

        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            //Toast.makeText(this, "AdListActivity我进来了onDestroy", Toast.LENGTH_LONG).show();
            webView.stopLoading();
            webView.clearHistory();
            webView.clearCache(true);
            webView.destroy();
            webView = null;
        }
        if (null != timer) {
            timer.cancel();
            if (null != timer) {
                timer.purge();
            }
            timer = null;
        }
    }

    /**
     * 重写返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (null != webView && keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }

        if (webView != null) {
            webView.stopLoading();
            webView.clearHistory();
            webView.clearCache(true);
            webView.destroy();
            webView = null;
        }
        if (null != timer) {
            timer.cancel();
            if (null != timer) {
                timer.purge();
            }
            timer = null;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNoFirst) {
            if (null != webView) {
                webView.loadUrl("javascript:appRefresh()");
            }
        }
        isNoFirst = true;
    }

    /**
     * 请求权限后回调的方法
     */
    @SuppressLint("MissingPermission")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;//有权限没有通过
        if (REQUEST_CODE == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                    break;
                }
            }
        }
        if (hasPermissionDismiss) {//如果有没有被允许的权限
            showPermissionDialog();
        } else {
            //权限已经都通过了，可以将程序继续打开了
            //imei = SystemUtil.getDeviceId(this);
            openUrl();
        }
    }

    /**
     * 设置权限弹框
     */
    private void showPermissionDialog() {
        if (mPermissionDialog == null) {
            mPermissionDialog = new AlertDialog.Builder(this)
                    .setMessage("已禁用权限，请手动授予")
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            cancelPermissionDialog();
                            Uri packageURI = Uri.parse("package:" + getPackageName(AdListActivity.this));
                            Intent intent = new Intent(Settings.
                                    ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //关闭页面或者做其他操作
                            cancelPermissionDialog();
                            finish();
                        }
                    })
                    .create();
        }
        mPermissionDialog.show();
    }

    /**
     * 取消弹框
     */
    private void cancelPermissionDialog() {
        mPermissionDialog.cancel();
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static synchronized String getPackageName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断指定包名的app是否已经安装，并且把结果返回给H5
     *
     * @param packageName
     */
    @JavascriptInterface
    public void CheckInstall(final String packageName) {

        Log.i("name:", packageName);

        packagenameLocal = packageName;

        final boolean isInstalled = SystemUtil.isAppInstalled(AdListActivity.this, packageName);
        if (isInstalled) {
            if (null != webView) {
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        if (null != webView) {
                            webView.loadUrl("javascript:CheckInstall_Return(1)");

                            Log.i("name:", "1");
                        }
                    }
                });
            }
        } else {
            if (null != webView) {
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        if (null != webView) {
                            webView.loadUrl("javascript:CheckInstall_Return(0)");

                            Log.i("name:", "0");
                        }
                    }
                });
            }
        }
    }

    /**
     * 打开指定包名App
     *
     * @param packageName
     */
    @JavascriptInterface
    public void AwallOpen(String packageName) {
        doStartApplicationWithPackageName(packageName);
    }

    /**
     * 打开指定包名App
     *
     * @param packageName
     */
    @JavascriptInterface
    public void OpenAPP(String packageName) {
        doStartApplicationWithPackageName(packageName);
    }

    /**
     * Toast信息提示
     *
     * @param message
     */
    @JavascriptInterface
    public void popout(String message) {
        if (!TextUtils.isEmpty(message)) {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 刷新
     */
    @JavascriptInterface
    public void refresh() {
        if (null != webView) {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    if (null != webView) {
                        webView.reload();
                    }
                }
            });
        }
    }

    /**
     * 打开浏览器试玩
     *
     * @param url
     */
    @JavascriptInterface
    public void openBrowser(String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        startActivity(intent);
    }

    /**
     * 打开浏览器试玩
     *
     * @param url
     */
    @JavascriptInterface
    public void Browser(String url) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {

        }
    }

    /**
     * 判断原生下载安装状态
     *
     * @param showType
     * @param buttonType
     * @param buttonName
     * @param downUlr
     */
    @JavascriptInterface
    public void initPceggsData(final String showType, final String buttonType, final String buttonName, String downUlr) {

        Log.i("initPceggsData:", showType + "...." + buttonType + "..." + buttonName + "..." + downUlr);

        downUrlLocal = downUlr;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if ("0".equals(showType)) {
                    tv_start_download.setVisibility(View.GONE);
                } else {
                    tv_start_download.setVisibility(View.VISIBLE);
                }

                tv_start_download.setText(buttonName);

                if ("0".equals(buttonType)) {
                    tv_start_download.setEnabled(false);
                } else {
                    tv_start_download.setEnabled(true);
                }
            }
        });
    }

    /**
     * 老版本方法
     *
     * @param url
     */
    @JavascriptInterface
    public void AwallDownLoad(String url) {
        //另一种下载方式
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        startActivity(intent);
    }

    /**
     * 打开qq
     */
    @JavascriptInterface
    public void startQQConversation(String qq) {
        String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
        if (SystemUtil.isAppInstalled(AdListActivity.this, "com.tencent.mobileqq")) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } else {
            Toast.makeText(AdListActivity.this, "请检查QQ是否可用!", Toast.LENGTH_SHORT).show();
        }
    }

    class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progress = newProgress;
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (null != title && !view.getUrl().contains(title)) {
                tv_title.setText(title);
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 JsResult result) {
            Toast.makeText(AdListActivity.this, message, Toast.LENGTH_LONG).show();
            result.confirm();
            return true;
        }

        // For 3.0+ Devices (Start)
        // onActivityResult attached before constructor
        protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
        }


        // For Lollipop 5.0+ Devices
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }

            uploadMessage = filePathCallback;

            Intent intent = fileChooserParams.createIntent();
            try {
                startActivityForResult(intent, REQUEST_SELECT_FILE);
            } catch (ActivityNotFoundException e) {
                uploadMessage = null;
                Toast.makeText(getBaseContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
                return false;
            }
            return true;
        }

        //For Android 4.1 only
        protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
        }

        protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
        }
    }

    class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);
        }

        @Override
        public void onPageFinished(WebView webView, String s) {
            super.onPageFinished(webView, s);

            if (null != timer) {
                timer.cancel();
                if (null != timer) {
                    timer.purge();
                }

                timer = null;
            }

            progress = 0;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();  // 接受所有网站的证书
        }
    }

    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 2;


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (requestCode == REQUEST_SELECT_FILE) {
                if (uploadMessage == null)
                    return;
                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
                uploadMessage = null;
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
            // Use RESULT_OK only if you're implementing WebView inside an Activity
            Uri result = intent == null || resultCode != AdListActivity.RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else
            Toast.makeText(getBaseContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
    }

    //在你下载完成的时候调用这个方法 就ok啦
    public void install(Context context, File file, String authorities) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //兼容8.0
            boolean haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {
                //TODO  去开启权限  可以添加一个AlertDialog 提示
                Uri parse = Uri.parse("package:" + context.getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, parse);
                startActivity(intent);
            } else {
                installOther(context, file, authorities);
            }
        } else {
            installOther(context, file, authorities);
        }
    }

    public void installOther(Context context, File file, String authorities) {

        if (!file.exists()) {
            return;
        }

        if (TextUtils.isEmpty(authorities)) {
            authorities = "com.pceggs.workwall.fileprovider";
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//兼容7.0
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, authorities, file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        startActivity(intent);
    }
}
